package com.geovis.emergency.spd.biz.system.wrapper;

import cn.hutool.core.util.StrUtil;
import com.geovis.common.core.constant.CommonConstants;
import com.geovis.emergency.spd.entity.system.pojo.node.INode;

import java.util.List;

public class ForestNodeMerger {
    public ForestNodeMerger() {
    }

    public static <T extends INode<T>> List<T> merge(List<T> items) {
        ForestNodeManager<T> forestNodeManager = new ForestNodeManager(items);
        items.forEach((forestNode) -> {
            if (StrUtil.isNotBlank(forestNode.getParentId())) {
                if (CommonConstants.TREE_ROOT_CODE.equals(forestNode.getParentId())){
                    forestNodeManager.addParentId(forestNode.getId());
                }else {
                    INode<T> node = forestNodeManager.getTreeNodeAt(forestNode.getParentId());
                    if (node != null) {
                        node.getChildren().add(forestNode);
                    } else {
                        forestNodeManager.addParentId(forestNode.getId());
                    }
                }

            }

        });
        return forestNodeManager.getRoot();
    }
}
